<?php
/**
 * Created by PhpStorm.
 * User: 14775
 * Date: 2017/9/4
 * Time: 14:07
 */

namespace Common\Model;


use Think\Exception;
use Common\ModelSQ\ERPUser;
class PromotionCouponModel extends CommonModel
{


    /**
     * 积分兑换优惠券
     * @param $couponId
     * @param $memberId
     * @return int
     */
    public function receiveCoupon($couponId, $memberId,$params)
    {
        $couponModel = new PromotionCouponModel();
        $memberModel = new MembersModel();
        $couponCodeModel = new PromotionCouponCodeModel();

        //$curDatetime = date('Y-m-d H:i:s');
        $coupon = $couponModel->where(array('id' => $couponId, 'use_flg' => 1))->find();
        //$coupon = $couponModel->where(array('id' => $couponId, 'use_flg' => 1, 'start_date' => array('elt', $curDatetime), 'end_date' => array('egt', $curDatetime)))->find();

        if (!$coupon) {
            return 404; //优惠券不存在
        }

        /*查询erp系统中用户积分数量*/
        $bonus_point=0;
        $erpUser = new ERPUser();

        //查询会员信息
        $data = array(
            'telephone' =>"{$params['telephone']}",
        );
        $erp_userinfo = $erpUser->getMember($data);
        if ($erp_userinfo['success'] && $erp_userinfo['code'] == 1000) {
            $bonus_point = isset($erp_userinfo['data']['currentbonus']) ? $erp_userinfo['data']['currentbonus'] : 0;
        }
        /*查询erp系统中用户积分数量 ============end */

        /*预扣减用户实际积分*/
        if ( $bonus_point <= 0|| ($bonus_point- $coupon['exintegral']) < 0){
            return 402; //用户积分不足
        }
        /*预扣减用户实际积分================end*/

        try {

            $couponModel->startTrans();

            //setp 1.增加优惠券已被领取的数量
            $result = $couponModel->where(array('id' => $couponId, 'total_num>get_num'))->setInc('get_num', 1);

            if (!$result) {
                $couponModel->rollback();
                return 401; //已领取完
            }

            //setp 2.扣除用户的积分
            $result = $memberModel->where(array('id' => $memberId, 'integral' => array('egt' , $coupon['exintegral'])))->setDec('integral', $coupon['exintegral']);

            if (!$result) {
                $couponModel->rollback();
                return 402; //用户积分不足
            }

            $couponCode = array(
                'code' => substr(md5($couponId . $memberId . microtime(true)), 8, 16),
                'create_time' => date('Y-m-d H:i:s'),
                'coupon_id' => $couponId,
                'member_id' => $memberId,
                'coupon_type' => $coupon['coupon_type'],
                'amount' => $coupon['amount'],
                'limit_money' => $coupon['coupon_type'],
                'start_date' => $coupon['start_date'],
                'end_date' => $coupon['end_date'],
                'use_type' => $coupon['use_type'],
                'merchant_id' => $coupon['merchant_id']
            );

            $couponCodeModel->add($couponCode);


            /*实际扣除积分数量*/
            $request_params= array(
                'member_code'=>$params['member_code'],
                'bonus_date'=>date('Y-m-d'),
                'bonus_time'=>date('H:i:s'),
                'bonus_type'=>'03', //积分调整
                'bonus_point'=>($bonus_point-$coupon['exintegral']), //扣减积分
                'doc_no'=>$couponId,
                'store_code'=>$couponId,
                'store_name_sc'=>'优惠劵兑换积分',
                'bonus_description'=>'01',
            );

            /*实际扣除积分数量=========================end*/
            $result_resp = $erpUser->bonusSync($request_params);
            if ( !$result_resp['success'] || $result_resp['code'] !=1000 ){
                $couponModel->rollback();
                return 402; //用户积分不足
            }
            $couponModel->commit();
            return 200; //成功
        } catch (Exception $ex) {
            $couponModel->rollback();
            return 500;//错误
        }
    }


    public function useCoupon($code)
    {
        $code_model = new PromotionCouponCodeModel();

        $coupon_code = $code_model->where(array('code' => $code, 'use_flg' => 1))->find();
        if (!$coupon_code) {
            return array('code' => 404, 'message' => '优惠券不存在');
        }

        if ($coupon_code['use_date']) {
            return array('code' => 404, 'message' => '优惠券已被使用','data'=>array('use_date'=>$coupon_code['use_date']));
        }


        try {
            $code_model->startTrans();

            $result = self::where(array('id' => $coupon_code['coupon_id'], 'get_num>use_num'))->setInc('use_num', 1);

            if (!$result) {
                $code_model->rollback();
                return array('code' => 500, 'message' => '系统异常,请联系相关人员'); //已领取完
            }

            $code_model->where(array('code' => $code))->save(array('use_date' => date('Y-m-d H:i:s')));

            $code_model->commit();
            return array('code' => 200, 'message' => 'ok');
        } catch (Exception $ex) {
            $code_model->rollback();
            return array('code' => 500, 'message' => '系统错误,请重试');
        }
    }
}